import sqlite3
from datetime import datetime
import os
import logging

class DatabaseManager:
    def __init__(self, db_path=None):
        if db_path is None:
            # 获取项目根目录
            project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            # 在项目根目录下创建数据库文件
            self.db_path = os.path.join(project_root, 'weibo_comments.db')
        else:
            self.db_path = db_path
        
        logging.info(f"数据库文件路径: {self.db_path}")
        self.init_database()
    
    def init_database(self):
        """初始化数据库表结构"""
        try:
            # 确保数据库文件所在目录存在
            os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
            
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 检查表是否存在
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='comments'")
            table_exists = cursor.fetchone() is not None
            
            if not table_exists:
                # 如果表不存在，创建新表
                cursor.execute('''
                CREATE TABLE comments (
                    comment_id TEXT PRIMARY KEY,
                    created_at TEXT,
                    user_id TEXT,
                    user_name TEXT,
                    user_city TEXT,
                    like_counts INTEGER,
                    reply_counts INTEGER,
                    content TEXT
                )
                ''')
            else:
                # 如果表存在，检查是否需要添加列
                cursor.execute("PRAGMA table_info(comments)")
                columns = [column[1] for column in cursor.fetchall()]
                
                if 'reply_counts' not in columns:
                    cursor.execute('ALTER TABLE comments ADD COLUMN reply_counts INTEGER')
            
            # 创建索引
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_comment_id ON comments(comment_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_user_id ON comments(user_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_created_at ON comments(created_at)')
            
            conn.commit()
            logging.info("数据库表创建/更新成功")
        except Exception as e:
            logging.error(f"创建/更新数据库表时出错: {e}")
            raise
        finally:
            conn.close()
    
    def save_comment(self, comment_data):
        """保存评论数据到数据库"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        try:
            cursor.execute('''
            INSERT OR REPLACE INTO comments (
                comment_id, created_at, user_id, user_name,
                user_city, like_counts, reply_counts, content
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                comment_data['comment_id'],
                comment_data['created_at'],
                comment_data['user_id'],
                comment_data['user_name'],
                comment_data['user_city'],
                comment_data['like_counts'],
                comment_data['reply_counts'],
                comment_data['content']
            ))
            
            conn.commit()
            logging.info(f"成功保存评论: {comment_data['comment_id']}")
            return True
        except Exception as e:
            logging.error(f"保存评论时出错: {e}")
            conn.rollback()
            return False
        finally:
            conn.close()
    
    def get_comment_count(self):
        """获取评论总数"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute('SELECT COUNT(*) FROM comments')
        count = cursor.fetchone()[0]
        conn.close()
        return count 